/*
 * StorageApplication.cpp
 *
 *  Created on: 2017年3月5日
 *      Author: chuanjiang.zh
 */

#include "TSingleton.h"
#include "CLog.h"
#include "Path.h"
#include "BasicMacro.h"
#include "Version.h"
#include "MediaWriter.h"
#include "StorageApplication.h"


typedef comn::Singleton< StorageApplication >		ApplicationSingleton;

StorageApplication& StorageApplication::instance()
{
	return ApplicationSingleton::instance();
}

StorageApplication::StorageApplication()
{
}

StorageApplication::~StorageApplication()
{
}

int StorageApplication::init()
{
	setupLog();

	CLog::info("MediaStorage %s\n", APP_VERSION);

	av::MediaWriterFactory::startup();

	std::string configPath = getConfigPath();
	if (!AppConfig::instance().load(configPath))
	{
		CLog::warning("can not load config: %s\n", configPath.c_str());
	}


	return 0;
}

void StorageApplication::quit()
{

	av::MediaWriterFactory::cleanup();

	CLog::cleanup();

}

std::string StorageApplication::getConfigPath()
{
#ifdef WIN32
	std::string workDir = comn::Path::getWorkDir();
	std::string pathList[] =
	{
		".",
		"../bin",
        "../MediaStorage",
		workDir
	};

#else
	std::string pathList[] =
	{
		".",
        "/usr/etc/MediaStorage",
		"/usr/etc",
		"/etc"
	};
#endif //

	return comn::Path::findFile(pathList, ARRAY_SIZE(pathList), "MediaStorage.ini");
}

std::string StorageApplication::getLogConfigPath()
{
#ifdef WIN32
	std::string workDir = comn::Path::getWorkDir();
	std::string pathList[] =
	{
		".",
		"../bin",
        "../setup",
		workDir
	};

#else
	std::string pathList[] =
	{
		".",
        "/usr/etc/MediaStorage",
		"/usr/etc",
		"/etc"
	};
#endif //

	return comn::Path::findFile(pathList, ARRAY_SIZE(pathList), "MediaStorageLog.ini");
}

void StorageApplication::setupLog()
{
	std::string filepath = getLogConfigPath();
	int ret = CLog::startup(filepath.c_str());
	if (ret != 0)
	{
		CLog::setLogger(CLog::COUT, CLog::kNone, 0);
	    CLog::setLogger(CLog::DEBUGWINDOW, CLog::kNone, 0);
	}
}

std::string StorageApplication::getDbPath()
{
	return AppConfig::instance().get("DB.Path", AppConst::DB_FILE);
}
